package com.zbxj.wyz.service;

import com.zbxj.wyz.domain.TrueOrFalse;
import com.zbxj.wyz.domain.dto.ChoiceToExamDto;
import com.zbxj.wyz.domain.dto.Result;
import com.zbxj.wyz.domain.dto.TrueOrFalseDto;

import com.zbxj.wyz.domain.dto.TrueOrFalseToExamDto;
import com.zbxj.wyz.mapper.TrueOrFalseMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Set;

@Service

public class TrueOrFalseService {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    TrueOrFalseMapper trueOrFalseMapper;
    //查
    @Cacheable(cacheNames="TrueOrFalseByCondition")
    public List<TrueOrFalseDto> getTrueOrFalseByCondition(String courseName, String trueOrFalseDifficulty, String trueOrFalseAudit,String searchValue){

        return trueOrFalseMapper.getTrueOrFalseByCondition(courseName,trueOrFalseDifficulty,trueOrFalseAudit,searchValue);
    };

    //改
    public Result updateTrueOrFalse(TrueOrFalse trueOrFalse){
        if (trueOrFalseMapper.updateTrueOrFalse(trueOrFalse)>0){
            return new Result<>().ok("更新判断题成功");
        }else
            return  new Result<>().ok("更新判断题失败");
    }

    //审核
    public  Result auditTrueOrFalse(TrueOrFalse trueOrFalse){
        if (trueOrFalseMapper.auditTrueOrFalse(trueOrFalse)>0){
            return new Result<>().ok("审核判断题成功");
        }else{
            return new Result<>().ok("审核判断题失败");
        }
    }
    public Result addTrueOrFalse(TrueOrFalse trueOrFalse){
        if (trueOrFalseMapper.addTrueOrFalse(trueOrFalse) > 0)
            return new Result().ok("增加选择题成功");
        else
            return new Result().serverError("增加选择题失败");
    }

    //删
    @CacheEvict(cacheNames="TrueOrFalseByCondition")
    public Result deleteTrueOrFalse(TrueOrFalse trueOrFalse){
        //删除redis中所有以ChoiceByCondition开头的key,目的是刷新缓存
        Set<String> keys = redisTemplate.keys("TrueOrFalseByCondition*");
        if (!CollectionUtils.isEmpty(keys)) {
            redisTemplate.delete(keys);
        }

        //更新数据库
        if(trueOrFalseMapper.deleteTrueorfalse(trueOrFalse) > 0)
            return new Result().ok("软删除选择题成功");
        else
            return new Result().serverError("软删除选择题失败");
    }

    public Result getAllTrueOrFalseToExam(String courseName, String trueOrFalseDifficulty){
        List<TrueOrFalseToExamDto> trueOrFalseList = trueOrFalseMapper.getAllTrueOrFalseToExam(courseName, trueOrFalseDifficulty);
        if(!trueOrFalseList.isEmpty())
            return new Result().ok("获取选择题列表（试卷用途）成功",trueOrFalseList);
        else
            return new Result().serverError("获取选择题列表（试卷用途）失败");
    }

}
